'use strict';
/**
 * U:{uid:用户唯一id,R:{K:游戏类型ID,S:游戏房间ID,T:桌子号,C:椅子号}} 
 */
module.exports.run = function(d,s,req){
    const bs = require("../module/base");
    switch(d[1]){
        case 1:{ //模拟用户
            if(!bs.checkParam(["acc","channelid","gametp"], d)) return;
            if(!isNaN(d[2].acc) || d[2].channelid != 1) return;

            bs.DB.query(`SELECT A.*,B.score,B.bank FROM users A inner join gamesocre B ON A.userid=B.userid WHERE account=$1`, (rs)=>{
                if(rs.rows.length) loginEnd(rs,d,s,req);
                else createUser(req, d, s);
            }, [d[2].acc])
            break;
        }
    }
}

/** 登录完成 */
function loginEnd(rs, d, s, req){
    const bs = require("../module/base");
    if(rs && rs.rows.length){
        s.U = {uid:rs.rows[0].userid};
        if(s.U.uid in USERMAP){
            USERMAP[s.U.uid].close();
        } 
        d[2] = rs.rows[0];

        USERMAP[s.U.uid] = s;
        bs.DB.log("loginlog", [s.U.uid,d[2].password,req.connection?req.connection.remoteAddress:"",d[2].channelid,d[2].macnum||""]);
    }else return bs.sendE(s, 3);
    bs.send(s, d);

    //记录在线玩家
    bs.RS(0).HSET("ONLINE:" + s.U.gametp, s.U.uid, Date.now());
}

/** 创建账号 */
function createUser(req, d, s){
    const bs = require("../module/base");
    bs.DB.query(`INSERT INTO users(account,pwd,nickname,headimg,regtime,channelid,macnum) VALUES($1,$2,$3,$4,NOW(),NOW(),$5) RETURNING *`,(rs)=>{
        bs.DB.query("INSERT INTO gamescore(userid,score,bank) VALUES($1,10000,0)",(rs2)=>{
            rs.rows[0].score = rs2.rows[0].score;
            rs.rows[0].bank = rs2.rows[0].bank;
            loginEnd(rs,d,s,req);
        },[rs.rows[0].userid]);
    }, [d[2].acc,d[2].password||"",d[2].nickname||"",d[2].headimg||"",req.connection.remoteAddress,d[2].channelid],d[2].macnum||"");
}